from flask import Flask, request, send_file
import os
from werkzeug.utils import secure_filename
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from utils import ConfigLoader
from model import OpenAIModel
from translator import PDFTranslator

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

@app.route('/translate', methods=['POST'])
def translate_pdf():
    if 'pdf' not in request.files:
        return "No file part", 400

    file = request.files['pdf']

    if file.filename == '':
        return "No selected file", 400

    if file:
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)

        # 加载配置
        config_loader = ConfigLoader('config.yaml')  # 需要配置文件的路径
        config = config_loader.load_config()

        model_name = config['OpenAIModel']['model']
        api_key = config['OpenAIModel']['api_key']
        model = OpenAIModel(model=model_name, api_key=api_key)

        # 实例化 PDFTranslator 类，并调用 translate_pdf() 方法
        translator = PDFTranslator(model)
        translated_file_path = translator.translate_pdf(file_path, 'pdf')  # 假设这个方法返回翻译后文件的路径

        return send_file(translated_file_path, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)
